﻿using aiot_paho_csharp;
using aiot_paho_mqtt_csharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using Newtonsoft.Json.Serialization;
using BilibiliDM_PluginFramework;

namespace muyu_monitor_plugin
{
    public class MuyuMonitor : BilibiliDM_PluginFramework.DMPlugin
    {
 
        private MuyuLogWindow mMuyuLogWindow;
        private MqttClient mMqttClient;
        private string mTopic;

        public MuyuMonitor()
        {
            this.Connected += MuyuMonitor_Connected;
            this.Disconnected += MuyuMonitor_Disconnected;
            this.ReceivedDanmaku += MuyuMonitor_ReceivedDanmaku;
            this.ReceivedRoomCount += MuyuMonitor_ReceivedRoomCount;
            this.PluginAuth = "wenfengtou";
            this.PluginName = "木鱼监视器";
            this.PluginCont = "qianmayi@gmail.com";
            this.PluginDesc = "根据弹幕类型发送mqtt消息";
            this.PluginVer = "v0.0.1";


            mMuyuLogWindow = new MuyuLogWindow(this);
        }

        public void OnLogWindowRendered()
        {
            //Task.Run(() => this.ConnectAliyun());
        }

        private void LogMuyu(String log)
        {
            Dispatcher.Invoke(() => mMuyuLogWindow.UpdateLog(log));
        }


        private void MuyuMonitor_ReceivedRoomCount(object sender, BilibiliDM_PluginFramework.ReceivedRoomCountArgs e)
        {
            Console.WriteLine("MuyuMonitor_ReceivedRoomCount");
        }

        private void handleComment(BilibiliDM_PluginFramework.ReceivedDanmakuArgs e)
        {
            ConfigData configData = ConfigManager.LoadConfig();
            foreach(MessageConfigItem item in configData.MessageConfigItems)
            {
                if (e.Danmaku.CommentText.Contains(item.ReceiveMessage))
                {
                    if (item.PublishTopic != null && item.SendMessage != null)
                    {
                        PublishMqttMessage(item.PublishTopic, item.SendMessage);
                    }
                }
            }
        }


        private void MuyuMonitor_ReceivedDanmaku(object sender, BilibiliDM_PluginFramework.ReceivedDanmakuArgs e)
        {
            if (e.Danmaku.MsgType == MsgTypeEnum.Comment)
            {
                handleComment(e);
            }
            Console.WriteLine("MuyuMonitor_ReceivedDanmaku");
            this.Log("MuyuMonitor_ReceivedDanmaku");
        }

        private void MuyuMonitor_Disconnected(object sender, BilibiliDM_PluginFramework.DisconnectEvtArgs e)
        {
            Console.WriteLine("MuyuMonitor_Disconnected");
        }

        private void MuyuMonitor_Connected(object sender, BilibiliDM_PluginFramework.ConnectedEvtArgs e)
        {
            Console.WriteLine("MuyuMonitor_Connected");
        }

        public override void Admin()
        {
            base.Admin();
            Console.WriteLine("Hello World");
            this.Log("Hello World");
            this.AddDM("Hello World", true);
            MainWindow w = new MainWindow();
            w.ShowDialog();
        }

        public override void Stop()
        {
            base.Stop();
            //請勿使用任何阻塞方法
            Console.WriteLine("Plugin Stoped!");
            this.Log("Plugin Stoped!");
            this.AddDM("Plugin Stoped!", true);
            if (mMuyuLogWindow != null && mMuyuLogWindow.IsActive)
            {
                mMuyuLogWindow.Close();
            }
            if (mMqttClient.IsConnected)
            {
                mMqttClient.Disconnect();
            }
        }


        public void PublishMqttMessage(String topic, String message)
        {
            LogMuyu("发布消息：" + "topic=" + topic + message);
            mMqttClient.Publish(topic, Encoding.UTF8.GetBytes(message));
        }

        public void QiaoMuyuOnce()
        {
            String message = GeneralMuyuPublishMsg(1, 1);
            PublishMqttMessage(mTopic, message);
        }
        private String GeneralMuyuPublishMsg(int woodenFishBlowCounts, int ledSwitch)
        {
            MuyuData muyuData = new MuyuData
            {
                Id = 123,
                Version = "1.0",
                Method = "thing.event.property.post",
                Params = new MuyuParam
                {
                    WoodenFishBlowCounts = woodenFishBlowCounts,
                    LedSwitch = ledSwitch
                }
            };

            // 定义 JsonSerializerSettings，指定 ContractResolver
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy() // 将属性名转换为小驼峰格式
                                                                   // 或者使用 SnakeCaseNamingStrategy 将属性名转换为蛇形命名格式
                                                                   //NamingStrategy = new SnakeCaseNamingStrategy()
                },
                Formatting = Formatting.Indented
            };

            // 将对象序列化为 JSON 字符串
            string json = JsonConvert.SerializeObject(muyuData, settings);

            // 输出生成的 JSON 字符串
            Console.WriteLine(json);
            return json;
        }

        // 连接阿里云
        private void ConnectAliyun()
        {
            LogMuyu("ConnectAliyun!");
            ConfigData configData = ConfigManager.LoadConfig();

            String productKey = configData.ProductKey ?? "k0re8OYQdFu";
            String deviceName = configData.DeviceName ?? "danmaku_monitor";
            String deviceSecret = configData.Secret ?? "3b52dbb8494c3e5f6b8eb90451dfcfa6";

            //计算Mqtt建联参数
            MqttSign sign = new MqttSign();
            sign.calculate(productKey, deviceName, deviceSecret);

            Console.WriteLine("username: " + sign.getUsername());
            Console.WriteLine("password: " + sign.getPassword());
            Console.WriteLine("clientid: " + sign.getClientid());

            //使用Paho链接阿里云物联网平台
            int port = 443;
            String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
            //broker = "47.100.6.214";

            mMqttClient = new MqttClient(broker, port, true, MqttSslProtocols.TLSv1_2, null, null);
            mMqttClient.Connect(sign.getClientid(), sign.getUsername(), sign.getPassword());

            LogMuyu("broker: " + broker + " Connected");
            Console.WriteLine("broker: " + broker + " Connected");

            //Paho Mqtt 消息订阅
            String mTopicReply = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";

            mMqttClient.MqttMsgPublishReceived += MqttPostProperty_MqttMsgPublishReceived;
            mMqttClient.Subscribe(new string[] { mTopicReply }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
            Console.WriteLine("subscribe: " + mTopicReply);

            //Paho Mqtt 消息发布


            mTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
            Console.WriteLine("publish mTopic: " + mTopic);
            String message = GeneralMuyuPublishMsg(8, 1);

            for (int i = 0; i < 1; i++)
            {
                PublishMqttMessage(mTopic, message);
                Thread.Sleep(500);
                Console.WriteLine("publish: " + message);
                LogMuyu("publish: " + message);
            }
           
        }

        private static void MqttPostProperty_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            Console.WriteLine("reply mTopic  :" + e.Topic);
            Console.WriteLine("reply payload:" + Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
        }

        // 回调函数的具体实现
        private void OnContentRenderedCallback()
        {
            Console.WriteLine("Content Rendered Callback Received!");
        }

        public override void Start()
        {
            base.Start();
            //請勿使用任何阻塞方法
            Console.WriteLine("Plugin Started!");
            mMuyuLogWindow.Show();
            mMuyuLogWindow.Topmost = false;
            mMuyuLogWindow.SetContentRenderedCallback(OnLogWindowRendered);
            this.ConnectAliyun();
            //Task.Run(() => ConnectAliyun());

            //Program.TestRun();

            //this.Log("Plugin Started!");
            // this.AddDM("Plugin Started!", true);
        }
    }
}
